﻿using MediatR;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 获取单位信息
    /// </summary>
    public class SearchUnitHandler : IRequestHandler<SearchUnitCommand, Result>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchUnitHandler> _logger;

        /// <summary>
        /// 单位仓储
        /// </summary>
        private readonly IBaseRepository<Units> _unitsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="unitsRepository"></param>
        public SearchUnitHandler(ILogger<SearchUnitHandler> logger,
            IBaseRepository<Units> unitsRepository)
        {
            _logger = logger;
            _unitsRepository = unitsRepository;
        }

        /// <summary>
        /// 获取单位信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchUnitCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _unitsRepository.GetAll()).ToListAsync();
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取单位信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取单位信息异常" + ex.Message;
                _logger.LogError("获取单位信息异常" + ex.Message);
            }
            return result;
        }
    }
}
